﻿// -----------------------------------------------------------------------
// <copyright file="MemoryInfo.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace TestApp
{
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Windows.Forms;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class MemoryInfo
    {
        IConsoleWriter writer;
        Timer memTimer;

        int allocatedMemory;
        int availbleMemoryMb;

        public MemoryInfo(IConsoleWriter writer)
        {
            this.writer = writer;

            // Only report if runtime > 2.5 seconds
            memTimer = new Timer();
            memTimer.Interval = 2500;
            memTimer.Tick += (s, e) =>
            {
                long current = GetAllocatedMemory();

                // Only report if memory difference > 10mb
                if (Math.Abs(current - allocatedMemory) > 10)
                {
                    allocatedMemory = (int)current;
                    this.writer.WriteLine(Color.Gray, "Currently allocated memory: " + allocatedMemory + "MB");
                }
            };

            try
            {
                var memory = new PerformanceCounter("Memory", "Available MBytes");
                availbleMemoryMb = (int)memory.NextValue();
            }
            catch (Exception)
            {
            }
        }

        public long GetAllocatedMemory()
        {
            Process p = Process.GetCurrentProcess();

            try
            {
                return p.PrivateMemorySize64 / 1048576;
            }
            catch (Exception)
            {
            }

            return 0;
        }

        public void StartReporting()
        {
            allocatedMemory = 100;
            memTimer.Start();
        }

        public void StopReporting()
        {
            memTimer.Stop();
        }
    }
}
